<template>
  <div class="payment-container" style="margin-bottom: 50px; padding-bottom: 10px;">
    <van-nav-bar title="支付" left-text="" left-arrow fixed @click-left="onClickLeft">
      <template #left>
        <van-icon name="arrow-left" size="24" color="gray" />
      </template>
    </van-nav-bar>

    <div class="content">
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <van-loading type="spinner" color="#4f46e5" />
        <p class="loading-text">正在加载订单信息...</p>
      </div>
      
      <!-- 订单信息，仅在非加载状态显示 -->
      <template v-else>
        <!-- 订单信息 -->
        <div class="order-card">
          <h2 class="section-title">订单信息</h2>
          <div class="order-info">
            <div class="task-info">
              <div class="flex justify-between items-start mb-2">
                <h3 class="task-title">{{ orderInfo.taskTitle }}</h3>
                <span class="task-price">¥{{ orderInfo.orderAmount }}</span>
              </div>
              <p class="task-address">{{ orderInfo.taskAddress }}</p>
              <div class="task-time">
                <span class="time-item"><van-icon name="calendar-o" /> {{ orderInfo.taskDate }}</span>
                <span class="time-item"><van-icon name="clock-o" /> {{ orderInfo.taskTime }}</span>
              </div>
            </div>
            <div class="price-details">
              <div class="price-item">
                <span class="price-label">订单金额</span>
                <span class="price-value">¥{{ orderInfo.orderAmount.toFixed(2) }}</span>
              </div>
              <div class="price-item">
                <span class="price-label">平台服务费</span>
                <span class="price-value">¥{{ orderInfo.platformFee.toFixed(2) }}</span>
              </div>
              <div class="price-item" v-if="orderInfo.couponAmount > 0">
                <span class="price-label">优惠券</span>
                <span class="price-value discount">-¥{{ orderInfo.couponAmount.toFixed(2) }}</span>
              </div>
            </div>
            <div class="total-price">
              <span class="total-label">实付金额</span>
              <span class="total-value">¥{{ calculateTotalPrice() }}</span>
            </div>
          </div>
        </div>
        
        <!-- 支付方式 -->
        <div class="payment-method-card">
          <h2 class="section-title">支付方式</h2>
          
          <div class="payment-methods">
            <div class="payment-method-item selected">
              <div class="method-info">
                <div class="method-icon balance-icon">
                  <van-icon name="balance-o" />
                </div>
                <div class="method-details">
                  <h3 class="method-name">余额支付</h3>
                  <p class="method-desc">当前余额: ¥{{ userBalance.toFixed(2) }}</p>
                </div>
              </div>
              <van-icon name="success" class="check-icon" />
            </div>
          </div>
        </div>
        
        <!-- 支付按钮 -->
        <van-button 
          class="pay-button" 
          type="primary" 
          color="#4f46e5" 
          block 
          :loading="isSubmitting"
          @click="submitPayment"
          :disabled="userBalance < parseFloat(calculateTotalPrice())"
        >
          确认支付 ¥{{ calculateTotalPrice() }}
        </van-button>
        
        <p v-if="userBalance < parseFloat(calculateTotalPrice())" class="balance-warning">
          余额不足，请先充值
        </p>
        
        <!-- 协议提示 -->
        <p class="agreement-text">
          点击"确认支付"，表示您同意<span class="agreement-link" @click="showAgreement('service')">《服务协议》</span>和<span class="agreement-link" @click="showAgreement('payment')">《支付协议》</span>
        </p>
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog } from 'vant'
import network from '../network'

const router = useRouter()
const route = useRoute()
const taskId = ref(Number(route.params.id) || 0)
const orderId = ref(Number(route.params.orderId) || 0)

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 订单信息
const orderInfo = reactive({
  orderId: 0,
  taskId: 0,
  employerId: 0,
  workerId: 0,
  applicationId: 0,
  taskTitle: '',
  taskAddress: '',
  taskDate: '',
  taskTime: '',
  orderAmount: 0,
  platformFee: 0,
  actualAmount: 0,
  orderStatus: 0,
  paymentStatus: 0,
  startTime: '',
  endTime: '',
  cancelReason: '',
  createTime: '',
  updateTime: '',
  couponAmount: 0
})

const isSubmitting = ref(false)
const userBalance = ref(0)
const isLoading = ref(true) // 添加加载状态标志

// 计算总价
const calculateTotalPrice = () => {
  return (orderInfo.actualAmount - orderInfo.couponAmount).toFixed(2)
}

// 获取订单信息
const fetchOrderInfo = async () => {
  try {
    if (orderId.value) {
      // 延迟两秒再发送请求
      await new Promise(resolve => setTimeout(resolve, 2000))
      
      const res: any = await network.getOrderDetail(orderId.value)
      if (res && res.code === 100) {
        const data = res.data
        Object.assign(orderInfo, {
          orderId: data.orderId,
          taskId: data.taskId,
          employerId: data.employerId,
          workerId: data.workerId,
          applicationId: data.applicationId,
          orderAmount: data.orderAmount,
          platformFee: data.platformFee,
          actualAmount: data.actualAmount,
          orderStatus: data.orderStatus,
          paymentStatus: data.paymentStatus,
          startTime: data.startTime,
          endTime: data.endTime,
          cancelReason: data.cancelReason,
          createTime: data.createTime,
          updateTime: data.updateTime,
          couponAmount: data.couponAmount || 0
        })
        
        // 获取任务详情
        await fetchTaskDetail(data.taskId)
      } else {
        showToast('获取订单信息失败')
      }
    } else {
      showToast('订单参数错误')
    }
  } catch (error) {
    console.error('获取订单信息失败:', error)
    showToast('获取订单信息失败，请稍后重试')
  } finally {
    isLoading.value = false // 无论成功失败，都结束加载状态
  }
}

// 获取任务详情
const fetchTaskDetail = async (taskId: number) => {
  try {
    if (!taskId) {
      console.error('任务ID为空')
      return
    }
    
    const res: any = await network.getTaskDetail(taskId)
    if (res.data && res.data.code === 100) {
      const taskData = res.data.data
      
      // 更新任务相关信息
      orderInfo.taskTitle = taskData.taskTitle || '未知任务'
      orderInfo.taskAddress = taskData.taskAddress || '未知地址'
      
      // 处理任务时间
      if (taskData.startTime) {
        const timeParts = taskData.startTime.split(' ')
        orderInfo.taskDate = timeParts[0] || ''
        orderInfo.taskTime = timeParts[1] || ''
      } else if (orderInfo.startTime) {
        // 如果任务没有时间，尝试使用订单的开始时间
        const timeParts = orderInfo.startTime.split(' ')
        orderInfo.taskDate = timeParts[0] || ''
        orderInfo.taskTime = timeParts[1] || ''
      }
    } else {
      console.error('获取任务详情失败')
    }
  } catch (error) {
    console.error('获取任务详情失败:', error)
  }
}

// 获取用户余额
const fetchUserBalance = async () => {
  try {
    const res: any = await network.getWalletInfo()
    if (res && res.code === 100) {
      userBalance.value = res.data.balance || 0
    }
  } catch (error) {
    console.error('获取用户余额失败:', error)
  }
}

// 提交支付
const submitPayment = async () => {
  try {
    // 检查余额是否足够
    if (userBalance.value < parseFloat(calculateTotalPrice())) {
      showToast('余额不足，请先充值')
      return
    }
    
    isSubmitting.value = true
    
    // 构建支付数据
    const paymentData = {
      orderId: orderInfo.orderId,
      paymentAmount: parseFloat(calculateTotalPrice()),
      paymentMethod: 'BALANCE',
      paymentStatus: 0, // 初始状态：待支付
      paymentIp: '', // 由后端获取
    }
    
    const res:any = await network.submitPayment(paymentData)
    if (res && res.code === 100) {
      // 保存返回的支付ID
      const paymentId = res.data.paymentId
      
      showToast({
        message: '支付成功',
        type: 'success'
      })
      
      // 余额支付，直接跳转到支付成功页面
      router.back()
    } else {
      showToast({
        message: res?.data?.message || '支付失败',
        type: 'fail'
      })
    }
  } catch (error) {
    console.error('支付失败:', error)
    showToast({
      message: '支付失败，请稍后重试',
      type: 'fail'
    })
  } finally {
    isSubmitting.value = false
  }
}

// 显示协议
const showAgreement = (type: 'service' | 'payment') => {
  const title = type === 'service' ? '服务协议' : '支付协议'
  showDialog({
    title,
    message: `这是${title}的内容，详细说明了用户在使用过程中的权利和义务...`,
    confirmButtonText: '我已阅读并同意',
    confirmButtonColor: '#4f46e5'
  })
}

// 页面加载时获取数据
onMounted(async () => {
  fetchOrderInfo() // 不使用await，让它异步执行
  await fetchUserBalance()
})
</script>

<style scoped>
.payment-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-top: 46px;
}

.content {
  max-width: 480px;
  margin: 0 auto;
  padding: 16px;
}

.order-card,
.payment-method-card {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 16px;
}

.order-info {
  display: flex;
  flex-direction: column;
}

.task-info {
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 16px;
  margin-bottom: 16px;
}

.task-title {
  font-size: 16px;
  font-weight: 500;
  color: #1e293b;
}

.task-price {
  font-size: 16px;
  font-weight: 600;
  color: #4f46e5;
}

.task-address {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 8px;
}

.task-time {
  display: flex;
  font-size: 14px;
  color: #64748b;
}

.time-item {
  display: flex;
  align-items: center;
  margin-right: 16px;
}

.time-item .van-icon {
  margin-right: 4px;
}

.price-details {
  margin-bottom: 16px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.price-label {
  color: #64748b;
}

.price-value {
  color: #1e293b;
}

.price-value.discount {
  color: #10b981;
}

.total-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #e5e7eb;
}

.total-label {
  font-size: 15px;
  font-weight: 500;
  color: #1e293b;
}

.total-value {
  font-size: 20px;
  font-weight: 700;
  color: #4f46e5;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.payment-method-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #4f46e5;
  border-radius: 12px;
  background-color: #f5f3ff;
}

.method-info {
  display: flex;
  align-items: center;
}

.method-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 8px;
  margin-right: 12px;
}

.method-icon .van-icon {
  font-size: 24px;
}

.balance-icon {
  background-color: #f5f3ff;
  color: #8b5cf6;
}

.method-details {
  display: flex;
  flex-direction: column;
}

.method-name {
  font-size: 15px;
  font-weight: 500;
  color: #1e293b;
  margin-bottom: 4px;
}

.method-desc {
  font-size: 12px;
  color: #64748b;
}

.check-icon {
  color: #4f46e5;
  font-size: 20px;
}

.pay-button {
  margin-bottom: 16px;
  height: 44px;
  font-size: 16px;
  border-radius: 22px;
}

.pay-button:disabled {
  opacity: 0.6;
}

.balance-warning {
  color: #ef4444;
  font-size: 14px;
  text-align: center;
  margin-bottom: 16px;
}

.agreement-text {
  font-size: 12px;
  color: #64748b;
  text-align: center;
}

.agreement-link {
  color: #4f46e5;
  cursor: pointer;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 16px;
}

.loading-text {
  margin-top: 16px;
  font-size: 14px;
  color: #64748b;
}
</style>